uuid = argv[1]
trunk_id = argv[2]

freeswitch.consoleLog("INFO","trunk_cache.lua start! uuid: "..uuid.." trunk id : "..trunk_id.."\n")

json = require "json"
api = freeswitch.API()

function getHashData( name )
	return api:executeString("hash select/realm/" .. name)
end

function setHashData( name, val )
	api:executeString("hash insert/realm/" .. name .. "/" .. val);
	freeswitch.consoleLog("info", "trunk_cache.lua set hash key " .. name .. "/" .. val .. "\n");
end

function setTrunkCallCount(trunk_calls) 
	local call_in_count = 0
	local call_out_count = 0;
	for k,v in pairs(trunk_calls) do
		if not api:executeString("uuid_exists " .. v.uuid) then
			freeswitch.consoleLog("info","uuid not exists " ..v.uuid)
			table.remove(trunk_calls,k)
		else
			if v.direction == "inbound" then
				call_in_count = call_in_count + 1
			else
				call_out_count = call_out_count +1
			end
		end
	end
	setHashData(trunk_id.."_call_in_count",call_in_count)
	setHashData(trunk_id.."_call_out_count",call_out_count)
	return trunk_calls
end

if trunk_id ~= nil and trunk_id ~= "" then
	--set variable
	api:executeString("uuid_setvar "..uuid.." trunk "..trunk_id)
	-- call in count 
	local trunk_calls = {}
	local trunk_calls_json = getHashData(trunk_id)
	if trunk_calls_json ~= nil and trunk_calls_json~= "" then
		freeswitch.consoleLog("INFO","get trunk call :" .. trunk_calls_json .. "\n")
		trunk_calls = json.decode(trunk_calls_json)
	end

	local channel = {}
	channel.uuid = uuid
	channel.name = api:executeString("uuid_getvar "..uuid.." channel_name") 
	channel.caller_id_number = api:executeString("uuid_getvar "..uuid.." caller_id_number")
	channel.destination_number = api:executeString("uuid_getvar "..uuid.." destination_number")
	channel.direction = api:executeString("uuid_getvar "..uuid.." direction")
	channel.create_at = api:executeString("strftime")

	table.insert(trunk_calls,channel)

	trunk_calls = setTrunkCallCount(trunk_calls)

	setHashData( trunk_id,json.encode(trunk_calls) )

end

